//
//  DateUtil.swift
//  maozzi-rss
//
//  Created by 帽子 on 2020/5/31.
//  Copyright © 2020 帽子. All rights reserved.
//

import SwiftUI

final class DateUtil {
    /* 将符合 format 格式的字符串 dateStr 转变为 date 类型
     * dateStr: 需要转变的字符串
     * format: 当前字符串格式
     */
    static func string2date(dateStr: String, format: String?) -> Date {
        let formatter = DateFormatter()
        formatter.locale = Locale.current
        formatter.dateFormat = format
        return formatter.date(from: dateStr)!
    }

    /* 将date 类型按照 format 格式输出字符串
     * date: 需要转变的 date 类型
     * format: 当前字符串格式
     */
    static func date2string(date: Date, format: String?) -> String {
        let formatter = DateFormatter()
        if format == "" {
            formatter.dateFormat = "yyyy年MM月dd日 HH:mm:ss"
        } else {
            formatter.dateFormat = format
        }
        return formatter.string(from: date)
    }

    /* 根据传入的 date 与当前时间相减返回特定格式
     * from: 起始日期
     * to: 结束日期
     */
    static func subtract(from: Date, to: Date) -> String {
        let fromMD = Calendar.current.dateComponents([.month, .day], from: from)
        let toMD = Calendar.current.dateComponents([.month, .day], from: to)
        let intervalMonth = Int(fabs(Double(toMD.month! - fromMD.month!)))
        let intervalDay = Int(fabs(Double(toMD.day! - fromMD.day!)))
        if intervalDay < 1 && intervalMonth == 0 {
            return date2string(date: from, format: "HH:mm")
        } else if intervalDay == 1 && intervalMonth == 0 {
            return "昨天\(date2string(date: from, format: "HH:mm"))"
        } else if intervalDay > 1 && intervalMonth == 0 {
            return "\(intervalDay)天前"
        } else {
            return date2string(date: from, format: "yyyy/MM/dd")
        }
    }
}
